package com.haiertvbic.tvnow;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.haiertvbic.tvnow.adapter.ProAdapater;
import com.haiertvbic.tvnow.common.AppManager;
import com.haiertvbic.tvnow.common.Constant;
import com.haiertvbic.tvnow.model.ProgramBean;
import com.haiertvbic.tvnow.model.ProgramItemBean;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.util.IsExit;
import com.haiertvbic.tvnow.util.LocateToast;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.SetActivityView;
import com.haiertvbic.tvnow.util.SwitchChannel;

/**
 * 获取节目数据，第二屏
 * 
 * @author sun
 * 
 */
public class SecondActivity extends Activity {

	private static final String TAG = "SecondActivity";
	// 获取节目成功
	protected static final int GET_PRO_SUC = 01;
	// 获取节目失败
	protected static final int GET_PRO_FAIL = 02;
	private int cha_id;
	private int which;
	private ListView pro_detail_lv;
	private ArrayList<ProgramBean> pro_list;
	public static View view;
	private boolean canToNext;
	private int currentCha = -200;
	private int switchCha = -200;
	private boolean canSwitch;
	public static ArrayList<ProgramBean> caches;
	private int sreen_height;
	private int sreen_width;
	private String cha_name;
	private TextView pro_name_tv;
	private ArrayList<View> itemViews = new ArrayList<View>();
	private TextView loading_tv;
	private Context context = SecondActivity.this;
	private Handler handle;
	private LinearLayout anim2_ll;

	/**
	 * 
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.pro_detail);
		view = SetActivityView.setActivityView(getWindow(), getWindowManager());
		sreen_height = getWindowManager().getDefaultDisplay().getHeight();
		sreen_width = getWindowManager().getDefaultDisplay().getWidth();
		Intent intent = getIntent();
		// cha_id = Integer.valueOf(intent.getStringExtra("CHA_ID"));
		cha_id = intent.getIntExtra("CHA_ID", -1);
		cha_name = intent.getStringExtra("CHA_NAME");
		// cha_id = 1;
//		cha_name = "湖南卫视";
		// EPGWeb.initSdcarDir(context);//测试用
		initView();
		AppManager.activityList.add(this);
		Animation inAnimation = AnimationUtils.loadAnimation(this,
				R.anim.slide_in_right);
		anim2_ll.setAnimation(inAnimation);
		anim2_ll.startAnimation(inAnimation);
		SLog.d(TAG, "第一屏传来的频道id是：" + cha_id + "频道名字" + cha_name);
		getResultPre();
		handle = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case GET_PRO_FAIL:
					loading_tv.setVisibility(View.VISIBLE);
					loading_tv.setText(R.string.getProFail);
					LocateToast.locateToast(
							SecondActivity.this,
							200,
							getResources().getString(
									R.string.get_program_failed));
					SLog.d(TAG, "GET_PRO_FAIL");
					break;
				case GET_PRO_SUC:
					// 获取数据成功，适配显示数据，消失加载数据的进度条
					if (pro_list != null && pro_list.size() > 0) {
						loading_tv.setVisibility(View.GONE);
						SLog.d(TAG, "得倒的节目长度========" + pro_list.size());
						pro_detail_lv.setAdapter(new ProAdapater(pro_list,
								sreen_width, context));
						pro_detail_lv.setVisibility(View.VISIBLE);
						pro_detail_lv.requestFocus();
						SLog.d(TAG, "GET_PRO_SUC--pro_list不等于空");
					}else {
						loading_tv.setVisibility(View.VISIBLE);
						loading_tv.setText(R.string.getProFail);
						SLog.d(TAG, "GET_PRO_SUC等于空");
					}
					canToNext = true;
					canSwitch = true;
					break;
				case 0:
					LocateToast.locateToast(
							SecondActivity.this,
							200,
							getResources().getString(
									R.string.read_change_msg_failed));
					break;

				case 4004500:
					LocateToast.locateToast(SecondActivity.this, 200,
							getResources().getString(R.string.change_success));
					currentCha = switchCha;
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;

				case 4004501:
					LocateToast.locateToast(
							SecondActivity.this,
							200,
							getResources().getString(
									R.string.channel_non_existent));
					break;

				case 4004502:
					LocateToast.locateToast(
							SecondActivity.this,
							200,
							getResources().getString(
									R.string.please_connect_crb));
					break;

				case 4004503:
					LocateToast.locateToast(SecondActivity.this, 200,
							getResources().getString(R.string.no_set_crb));
					break;

				case -2002:
					LocateToast.locateToast(SecondActivity.this, 200,
							getResources()
									.getString(R.string.connect_break_off));
					break;

				default:
					break;
				}

			}
		};
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		anim2_ll = (LinearLayout) findViewById(R.id.anim2_ll);
		pro_name_tv = (TextView) findViewById(R.id.pro_name_tv);
		pro_name_tv.setText(cha_name);
		loading_tv = (TextView) findViewById(R.id.loading_tv);
		pro_detail_lv = (ListView) findViewById(R.id.pro_detail_lv);
		pro_detail_lv.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

				which = arg2;
				// itemViews.add(arg1);
				// ProgramBean pro = null;
				// pro = (ProgramBean) arg0.getAdapter().getItem(arg2);
				// // 得倒那个返回的view并把颜色改了
				// ScreenshortHolder holder = new ScreenshortHolder();
				// for (int i = 0; i < itemViews.size(); i++) {
				// if (itemViews.get(i) != arg1) {
				// holder = (ScreenshortHolder) itemViews.get(i).getTag();
				// // holder.screenshort_background_ll
				// // .setBackgroundResource(R.color.gray_color);
				// holder.screenshort_background_ll
				// .setBackgroundColor(0x00333333);
				// holder.pro_tv.setTextColor(0x00FFFFFF);
				// holder.pro_stime_tv.setTextColor(0x00FFFFFF);
				// holder.toNext.setVisibility(View.GONE);
				// } else {
				// holder = (ScreenshortHolder) arg1.getTag();
				// // holder.screenshort_background_ll
				// // .setBackgroundResource(R.color.gray1_color);
				// holder.screenshort_background_ll
				// .setBackgroundColor(0xDF333333);
				// holder.pro_tv.setTextColor(0xFFFFFF66);
				// holder.pro_stime_tv.setTextColor(0xFFFFFF66);
				// // Constant.PRO_TYPE = 92 + "";
				// if (pro.getPtype().contains(Constant.PRO_TYPE)) {
				// holder.toNext.setVisibility(View.VISIBLE);
				// holder.toNext.setTextColor(0xFFFFFF66);
				// } else {
				// holder.toNext.setVisibility(View.GONE);
				// }
				// holder.screenshort_background_ll
				// .setVisibility(View.VISIBLE);
				// }
				// }

				// ProduceThread.seconds = 60;

			}

			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		pro_detail_lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				SLog.d(TAG, "在第二界面当前的频道id======" + arg2);
				if (canSwitch && currentCha != cha_id) {
					SwitchChannel.switchChannel(SecondActivity.this, cha_id,
							handle);
					switchCha = cha_id;
				}

				// ProduceThread.seconds = 60;
			}

		});
	}

	/**
	 * 得到节目的过程，开了一个线程和服务器交互获取数据
	 */
	public void getResultPre() {
		new Thread() {
			public void run() {
				try {
					pro_list = EPGWeb.getProgramList(SecondActivity.this,
							cha_id);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				if (pro_list == null) {
					handle.sendEmptyMessage(GET_PRO_FAIL);
					SLog.d(TAG, "发送GET_PRO_FAIL");
				} else {
					handle.sendEmptyMessage(GET_PRO_SUC);
					SLog.d(TAG, "发送GET_PRO_SUC");
				}

				// 获取电视剧pType
				try {
					ArrayList<ProgramItemBean> itemList = EPGWeb
							.getProgramItem(SecondActivity.this);
					int size = itemList.size();
					for (int index = 0; index < size; index++) {
						ProgramItemBean itemBean = itemList.get(index);
						if (itemBean.getName().equals("电视剧")) {
							Constant.PRO_TYPE = itemBean.getNode() + "";
							break;
						}
					}
				} catch (Exception e) {
					if (Constant.PRO_TYPE == null) {
						handle.sendEmptyMessage(GET_PRO_FAIL);
						SLog.d(TAG, "发送GET_PRO_FAIL和节目相关");
					}
				}
				// handle.sendEmptyMessage(GET_PRO_SUC);
			};
		}.start();

	}

	/**
	 * 处理按键事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// ProduceThread.seconds = 60;
		SLog.d(TAG, "在第二个界面你所按的键值是=====" + keyCode);
		if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			Intent intent = new Intent();
			intent.setClass(SecondActivity.this, TVNOWActivity.class);
			finish();
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			// ProduceThread.canRun = false;
			// ProduceThread.exit = false;
//			IsExit.isExit(this);
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			if (pro_list != null && which < pro_list.size()
					&& pro_list.get(which).getPtype() != null && canToNext
					&& pro_list.size() > 0) {

				if (pro_list.get(which).getPtype().contains(Constant.PRO_TYPE)) {
					// Animation outAnimation =
					// AnimationUtils.loadAnimation(this,
					// R.anim.slide_in_left);
					// view.setAnimation(outAnimation);
					// view.startAnimation(outAnimation);
					Intent intent = new Intent();
					intent.setClass(SecondActivity.this, ThreeAcitivity.class);
					intent.putExtra("PRO_ID", pro_list.get(which).getPid());
					intent.putExtra("PRO_NAME", pro_list.get(which).getPn());
					startActivity(intent);
					view.setVisibility(View.GONE);
				} else {
					LocateToast
							.locateToast(
									this,
									200,
									getResources()
											.getString(
													R.string.the_pro_is_not_Television_poly));

				}
			}

		}
		return super.onKeyDown(keyCode, event);
	}

}
